from flask import Blueprint,request
from flaskDemo.sql.mysql_db import mysql_db
from flaskDemo.config.config import Config
from flaskDemo.extensions.success import list_result
from flaskDemo.sql.sqlModel import SqlModel
#使用depart空间
depart = Blueprint('depart', __name__)
err = Config.ERR

@depart.route("/getDepartList",methods=['GET'])
def getDepartList():
    with mysql_db() as db:
        sql = f"select * from system_depart where pid = '0'"
        result = db.fetch_all(sql)

        def circulate_child(item):
            sql = f"select * from system_depart where pid = '{item['id']}'"
            child_result = db.fetch_all(sql)
            item["children"] = child_result
            if len(child_result) > 0:
                for itemChild in child_result:
                    circulate_child(itemChild)
            else:
                item["children"] = []
                return -1

        if len(result) > 0:
            for item in result:
                circulate_child(item)
        return list_result(result)

@depart.route("/addOrUpdateDepart",methods=['POST'])
def addOrUpdateDepart():
    params = request.json
    id = params.get("id")
    with mysql_db() as db:
        if id is not None and id != '':
            model = SqlModel("system_depart", [params])
            sql = model.update_sql()
            sql = f"{sql} where id = '{id}'"
            db.update(sql)
            db.conn.commit()
            return list_result()
        else:
            model = SqlModel("system_depart", [params])
            sql = model.insert_sql()
            db.insert(sql)
            db.conn.commit()
            return list_result()

@depart.route("/delDepart",methods=['POST'])
def delDepart():
    params = request.values
    id = params["id"]
    model = SqlModel("system_depart", [params])
    sql = model.delete_sql()
    sql = f"{sql} where id = '{id}' or find_in_set(id_path,'{id}');"
    with mysql_db() as db:
        db.delete(sql)
        db.conn.commit()
        return list_result()
